package com.pay.ioopos.support.serialport.custom;

import com.aggregate.pay.sanstar.enums.PayStatus;
import com.pay.ioopos.support.serialport.CmdParamException;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

/**
 * 输出指令：支付状态通知
 * @author moyq5
 * @since 2022/7/26
 */
public class SerialPortPayCmd2Status extends SerialPortPayCmd2Submit {
    private static int serialNo = 0;

    private PayStatus status;
    private String message;

    public SerialPortPayCmd2Status(BigDecimal amount, PayStatus status) {
        super(amount);
        this.status = status;
    }

    @Override
    protected SerialPortPayCmdType bizType() {
        return SerialPortPayCmdType.PAY_STATUS;
    }

    @Override
    protected int serialNo() {
        if (serialNo > 0xFFFF) {
            serialNo = 0;
        }
        return serialNo++;
    }

    @Override
    protected byte[] content() {
        if (null == status) {
            throw new CmdParamException("支付状态不能为空");
        }
        byte[] superContent = super.content();

        byte[] descr = new byte[0];
        if (null != message && !message.isEmpty()) {
            descr = message.getBytes(StandardCharsets.UTF_8);
        }
        if (descr.length > 0xFF) {
            throw new CmdParamException("支付状态描述过长：" + descr.length);
        }

        // 继承长度 + 状态（1）+ 描述长度值（1） + 描述长度
        byte[] content = new byte[superContent.length + 2 + descr.length];

        // 状态，1个字节
        content[superContent.length] = (byte) (status.ordinal() & 0xFF);

        // 状态描述长度，1个字节
        content[superContent.length + 1] = (byte) (descr.length & 0xFF);

        // 状态描述，任意长度
        if (descr.length > 0) {
            System.arraycopy(descr, 0, content, superContent.length + 2, descr.length);
        }

        return content;
    }

    public PayStatus getStatus() {
        return status;
    }

    public void setStatus(PayStatus status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
